#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <error.h>
#include <string.h>

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " <ip addr> <port>" << std::endl;
        return 1;
    }

    int sockfd;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        std::cerr << "Error creating socket: " << strerror(errno) << std::endl;
        return -1;
    }

    struct hostent* h;
    if ((h = gethostbyname(argv[1])) == NULL) {
        std::cerr << "Error resolving hostname: " << hstrerror(h_errno) << std::endl;
        return 1;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    memcpy(&server_addr.sin_addr, h->h_addr, h->h_length);
    server_addr.sin_port = htons(atoi(argv[2]));

    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        std::cerr << "error connect" << std::endl;
        close(sockfd);
        return -1;
    }

    for (int i = 0; i < 3; i ++) {
        int iret;
        char buffer[1024];
        sprintf(buffer, "%dst msg\n", i + 1);
        if ((iret = send(sockfd, buffer, strlen(buffer), 0)) <= 0) {
            std::cerr << "Error sending message: " << strerror(errno) << std::endl;
            break;
        }

        memset(buffer, 0, sizeof(buffer));
        if ((iret = recv(sockfd, buffer, sizeof(buffer) - 1, 0)) <= 0) {
            std::cerr << "Error receiving message: " << strerror(errno) << std::endl;
            break;
        }
        std::cout << "recv: " << buffer << std::endl;
        sleep(1);
    }

    close(sockfd);
} 